'use strict';

/**
 *  房间管理中心
 */
let roomexp = module.exports;

var Room = require('./Room');

var rooms = {};

var MaxRoomNum = 100;
var MaxRoomPlayer = 30;
var MaxFinder = 10;

//检查房间是不是空的
function isEmptyObject(obj) {
    for (var k in obj)
        return false;
    return true;
}
//

// //获取房间
roomexp.getRoomByID = function(value){
    for(var k in rooms){
        var room = rooms[k];
        if (room.roomid === value){
            return room;
        }
    }

    return null;
};
//
roomexp.addUserToRoom = function(user){
    for(var k in rooms){
        var room = rooms[k];
        if (room.GetUserNumber() < MaxRoomPlayer){
            room.AddUser(user);
            var data = user.strip();
            var channel = self.app.get('channelService').getChannel('syncChannel', true);
            channel.add(uid, self.sid);
            room.notifyMsgEnterRoom(channel, {user: data});
        }
    }
};
//
roomexp.getRoomNumber = function(){
    var num = 0;

    for (var k in rooms){
        ++num;
    }
    return num;

};
//
roomexp.setRoomToUse = function() {
    if (isEmptyObject(rooms) === false){
       //没有房间
       var room = new Room({roomid:1});
       rooms[room.roomid] = room;
    }else{
      //找到可用的房间
        var find = 0;
        for(var k in rooms){
            var room = rooms[k];
            if (room.GetRoomNumber() <= MaxRoomPlayer){
                find += 1;
            }
        }
        if (find === 0){
            var roomid = GetRoomNumber() + 1;
            var room = new Room({roomid:roomid});
            rooms[room.roomid] = room;
        }
    }
};



